package com.jit.BluetoothKey.utils;

import com.clj.fastble.utils.HexUtil;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

/**
 * Created by Administrator on 2018/2/27.
 */

public class BleControllerUtil {

    /**
     *  验证加密方法，回执外围蓝牙发送过来的数据
     * @param data  接收报文
     * @return
     * @throws Exception
     */
    public static String respondsSub(String sk,byte[] data) throws Exception {
        String s = HexUtil.formatHexString(data);
        String subData = s.substring(6, s.length() - 6); // 去除报文的头尾
        subData = subData+"55aa";  //补位55aa
        byte[] skBytes = HexUtil.hexStringToBytes(sk);
        byte[] respsData = encrypt(skBytes, HexUtil.hexStringToBytes(subData));  //根据秘钥SK 进行加密   000102030405060708090a0b0c0d55aa
        String s1 = HexUtil.formatHexString(respsData);
        if (s1.length()>26)
            subData = s1.substring(0,26);   //报文最多20 字节，大于20字节 截取前面部分（截取前13个字节）
        subData = "a55a4100" + subData + "00f5fa";   //拼接报文开头和结尾
        return subData;
    }

    private  static byte[] encrypt(byte[] key, byte[] clear) throws Exception {
        //受限于蓝牙报文20字节 加密传输只截取前20位 进行校验
        SecretKeySpec skeySpec = new SecretKeySpec(key, "AES");
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
        byte[] encrypted = cipher.doFinal(clear);
        return encrypted;
    }
}
